/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.userorder.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用户订单Controller
 * @author zhych
 * @version 2021-08-23
 */
@RestController
@RequestMapping(value = "/userorder/userOrder1")
public class UserOrderController1 extends BaseController {

	@Autowired
	private UserOrderService userOrderService;

	@ModelAttribute
	public UserOrder get(@RequestParam(required=false) String id) {
		UserOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = userOrderService.get(id);
		}
		if (entity == null){
			entity = new UserOrder();
		}
		return entity;
	}

	/**
	 * 用户订单列表数据
	 */
	@RequiresPermissions("userorder:userOrder:list")
	@GetMapping("list")
	public AjaxJson list(UserOrder userOrder, HttpServletRequest request, HttpServletResponse response) {
		userOrder.setDataScope(" and a.order_state in ('2', '6')");
		Page<UserOrder> page = userOrderService.findPage(new Page<UserOrder>(request, response), userOrder);
		// 退款总金额统计
		BigDecimal money = BigDecimal.ZERO;
		List<UserOrder> list = userOrderService.findList(userOrder);
		for (UserOrder order : list) {
			if (StringUtils.isNotBlank(order.getPayAmount()) && order.getOrderState().equals("6")) {
				money = money.add(new BigDecimal(order.getPayAmount()));
			}
		}
		return AjaxJson.success().put("page",page).put("money", money.setScale(2, BigDecimal.ROUND_HALF_UP));
	}

	/**
	 * 根据Id获取用户订单数据
	 */
	@RequiresPermissions(value={"userorder:userOrder:view","userorder:userOrder:add","userorder:userOrder:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(UserOrder userOrder) {
		return AjaxJson.success().put("userOrder", userOrder);
	}

	/**
	 * 保存用户订单
	 */
	@RequiresPermissions(value={"userorder:userOrder:add","userorder:userOrder:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(UserOrder userOrder, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(userOrder);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		userOrderService.save(userOrder);//保存
		return AjaxJson.success("保存用户订单成功");
	}


	/**
	 * 批量删除用户订单
	 */
	@RequiresPermissions("userorder:userOrder:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			userOrderService.deleteByLogic(new UserOrder(id));
		}
		return AjaxJson.success("删除用户订单成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("userorder:userOrder:export")
    @GetMapping("export")
    public AjaxJson exportFile(UserOrder userOrder, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "用户订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<UserOrder> page = userOrderService.findPage(new Page<UserOrder>(request, response, -1), userOrder);
    		new ExportExcel("用户订单", UserOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出用户订单记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("userorder:userOrder:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<UserOrder> list = ei.getDataList(UserOrder.class);
			for (UserOrder userOrder : list){
				try{
					userOrderService.save(userOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户订单记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条用户订单记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入用户订单失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入用户订单数据模板
	 */
	@RequiresPermissions("userorder:userOrder:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "用户订单数据导入模板.xlsx";
    		List<UserOrder> list = Lists.newArrayList();
    		new ExportExcel("用户订单数据", UserOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

    @RequestMapping("refund")
	public AjaxJson refund(String id) {
		UserOrder userOrder = userOrderService.get(id);
		Map<String, String> refund = userOrderService.refund(userOrder, appId, mchNo, mchSecret, certPath);
		if (refund.get("k").equals("0")) {
			return AjaxJson.success(refund.get("v"));
		} else {
			return AjaxJson.error(refund.get("v"));
		}
	}
}